﻿using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using DotNetCommon.Extensions;
using MySqlConnector;

namespace DBUtil.Provider.MySql
{
    public partial class MySqlAccess : DBAccess
    {

        #region Is系列: 判断表/视图/列/存储过程是否存在
        public async override Task<bool> IsProcedureExistAsync(string procName, CancellationToken cancellationToken = default(CancellationToken))
        {
            var sql = IsProcedureExistSql(procName);
            var r = await SelectScalarAsync<string>(sql);
            return r.IsNotNullOrEmptyOrWhiteSpace();
        }

        public async override Task<bool> IsTriggerExistAsync(string triggerName, CancellationToken cancellationToken = default(CancellationToken))
        {
            var sql = IsTriggerExistSql(triggerName);
            return await SelectScalarAsync<int>(sql, cancellationToken) > 0;
        }
        #endregion

        #region 使用SqlBulkCopy批量插入数据
        public override async Task BulkCopyAsync(DataTable dt, string tableName = null, int timeoutSeconds = 60 * 30, int notifyAfter = 0, Func<long, Task<bool>> callBack = null, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(tableName)) tableName = dt.TableName;
            if (string.IsNullOrWhiteSpace(tableName)) throw new Exception("必须指定要目的表名!");
            MySqlBulkCopy sbc = null;
            if (IsTransaction) sbc = new MySqlBulkCopy((MySqlConnection)CurrentConnection, (MySqlTransaction)CurrentTransaction);
            else if (IsSession) sbc = new MySqlBulkCopy((MySqlConnection)CurrentConnection);
            else sbc = new MySqlBulkCopy((MySqlConnection)GetNewConnection());

            sbc.BulkCopyTimeout = timeoutSeconds;
            sbc.DestinationTableName = tableName;
            sbc.NotifyAfter = notifyAfter;
            if (callBack != null) sbc.MySqlRowsCopied += async (object sender, MySqlRowsCopiedEventArgs e) =>
            {
                e.Abort = await callBack(e.RowsCopied);
            };
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sbc.ColumnMappings.Add(new MySqlBulkCopyColumnMapping(i, dt.Columns[i].ColumnName));
            }
            await sbc.WriteToServerAsync(dt);
        }
        #endregion
    }
}
